package com.uu.safeguard.controller;

import com.uu.safeguard.result.Result;
import com.uu.safeguard.result.ResultFactory;
import com.uu.safeguard.utils.DbUtil;
import com.uu.safeguard.utils.FileUtil;
import com.uu.safeguard.utils.JedisUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/upgrade")
public class StationUpgradeController {
    private Logger logger = LoggerFactory.getLogger(StationUpgradeController.class);
    /**
     * @Description: 设备版本查询
     * @Param: [token, params]
     **/
    @PostMapping("/queryVersion")
    public Result queryVersion(@RequestHeader("token")String token,
                               @RequestHeader("platformSn")@NotEmpty(message="platformSn 不能为空")String platformSn,
                               @RequestParam Map<String, String> params){
        String stationNo = params.get("stationNo");
        if (StringUtils.isEmpty(stationNo)){
            return ResultFactory.buildFailResult("缺少参数");
        }
        DbUtil db = new DbUtil();
        Map stationVersion = db.table("station").where(new ArrayList(){{
            add(new ArrayList(){{
                add("sn");
                add("=");
                add(stationNo);
            }});
            add(new ArrayList(){{
                add("platform_sn");
                add("=");
                add(platformSn);
            }});
        }}).find("sn,version");
        return ResultFactory.buildSuccessResult(stationVersion);
    }
    /**
     * @Description: 设备语音（模块）
     * @Param: [token, params]
     **/
    @PostMapping("/voiceModule")
    public Result voiceModule(@RequestHeader("token")String token,
                              @RequestHeader("platformSn")@NotEmpty(message="platformSn 不能为空")String platformSn,
                              @RequestParam Map<String, String> params){
        String stationNo = params.get("stationNo");
        String voice = params.get("voice");
        if (StringUtils.isEmpty(stationNo)||StringUtils.isEmpty(params.get("voice"))){
            return ResultFactory.buildFailResult("缺少参数");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stationNo",stationNo);
        jsonObject.put("voice",voice);
        DbUtil db = new DbUtil();
        //查看类型
        Map stationVersion = db.table("station").where(new ArrayList(){{
            add(new ArrayList(){{
                add("sn");
                add("=");
                add(stationNo);
            }});
            add(new ArrayList(){{
                add("platform_sn");
                add("=");
                add(platformSn);
            }});
        }}).find("sn,version,type");
        if (null == stationVersion){
            return ResultFactory.buildFailResult("非本平台设备或设备不存在");
        }
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(2); //插入带升级设备
        if ("3".equals(stationVersion.get("type"))){
            //System.out.println("类型："+stationVersion.get("type"));
            jedis.set("station_update_dc_voice", jsonObject.toString());
            jedis.close();
        }else{
            //System.out.println("类型2："+stationVersion.get("type"));
            jedis.set("station_update_voice", jsonObject.toString());
            jedis.close();
        }
        return ResultFactory.buildSuccessResult("成功");
    }
    /**
     * @Description: 设备音量
     * @Param: [token, params]
     **/
    @PostMapping("/modulation")
    public Result modulation(@RequestHeader("token")String token,
                             @RequestHeader("platformSn")@NotEmpty(message="platformSn 不能为空")String platformSn,
                             @RequestParam Map<String, String> params){
        String stationNo = params.get("stationNo");
        int vol = StringUtils.isEmpty(params.get("vol"))? 3 : Integer.parseInt(params.get("vol"));
        if (StringUtils.isEmpty(stationNo)){
            return ResultFactory.buildFailResult("缺少参数");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stationNo",stationNo);
        jsonObject.put("vol",vol);
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(2); //插入带升级设备
        jedis.set("station_voice_vol", jsonObject.toString());
        jedis.close();
        return ResultFactory.buildSuccessResult("成功");
    }
    /**
     * @Description: 设备重启
     * @Param: [token, params]
     **/
    @PostMapping("/reboot")
    public Result reboot(@RequestHeader("token")String token,
                         @RequestHeader("platformSn")@NotEmpty(message="platformSn 不能为空")String platformSn,
                         @RequestParam Map<String, String> params){
        String stationNo = params.get("stationNo");
        if (StringUtils.isEmpty(stationNo)){
            return ResultFactory.buildFailResult("缺少参数");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stationNo",stationNo);
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(2); //插入带升级设备
        jedis.set("station_restart", jsonObject.toString());
        jedis.close();
        return ResultFactory.buildSuccessResult("成功");
    }
    /**
     * @Description: 设备升级
     * @Param: [token, params]
     **/
    @PostMapping("/promote")
    public Result promote(@RequestHeader("token")String token,
                          @RequestHeader("platformSn")@NotEmpty(message="platformSn 不能为空")String platformSn,
                          @RequestParam Map<String, String> params){
        String stationNo = params.get("stationNo");
        String filePath = params.get("filePath");
        //filePath="./upgradeFile/A-V1-0-2.bin";
        if (StringUtils.isEmpty(stationNo)||StringUtils.isEmpty(filePath)){
            return ResultFactory.buildFailResult("缺少参数");
        }
        filePath = "./upgradeFile/" + filePath;
        System.out.println("filePath:"+filePath);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stationNo",stationNo);
        jsonObject.put("filePath",filePath);
        DbUtil db = new DbUtil();
        //查看类型
        Map stationVersion = db.table("station").where(new ArrayList(){{
            add(new ArrayList(){{
                add("sn");
                add("=");
                add(stationNo);
            }});
            add(new ArrayList(){{
                add("platform_sn");
                add("=");
                add(platformSn);
            }});
        }}).find("sn,version,type");
        if (null == stationVersion){
            return ResultFactory.buildFailResult("非本平台设备或设备不存在");
        }
        Jedis jedis = JedisUtil.getJedis();
        jedis.select(2); //插入带升级设备
        if ("3".equals(stationVersion.get("type"))){
            jedis.set("station_update_dc", jsonObject.toString());
            jedis.close();
        }else{
            jedis.set("station_update", jsonObject.toString());
            jedis.close();
        }
        return ResultFactory.buildSuccessResult("成功");
    }

    /**
     * @Description: 获取升级文件列表
     * @Param: [token, params]
     **/
    @PostMapping("/fileList")
    public Result fileList(@RequestHeader("token")String token,
                           @RequestHeader("platformSn")@NotEmpty(message="platformSn 不能为空")String platformSn,
                           @RequestParam Map<String, String> params){
        //这是需要获取的文件夹路径
        //String path = "/upgradeFile/";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String webappPath = request.getSession().getServletContext().getRealPath("/");
        String relativePath = "/upgradeFile/";
        String path = webappPath + relativePath;
        System.out.println("path:"+path);
        try {
            List file = FileUtil.getFile(path, 0);
            return ResultFactory.buildSuccessResult(file);
        }catch (NullPointerException e){
            return ResultFactory.buildFailResult("文件列表为空");
        }
    }
/*
    public static void main(String[] args) {
        //这是需要获取的文件夹路径
        String path = "/test";
        List file = FileUtil.getFile(path, 0);
        System.out.println(file);
    }
*/
}
